package malagaAcoge.controller.daos;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import malagaAcoge.model.entities.Abogado;
import malagaAcoge.model.entities.Historialpenal;
import malagaAcoge.utils.JPAUtils;

public class HistorialPenalDao {
	private static JPAUtils jpaUtils;
	protected static EntityManager em;

	public HistorialPenalDao() {
		jpaUtils = new JPAUtils();

	}
	public static void createHistorialpenal(Historialpenal historialPenal) {
		try {
			em = jpaUtils.getEntityManager();
			em.getTransaction().begin();
			em.persist(historialPenal);
			em.getTransaction().commit();
		} catch (Exception e) {
			System.out.println("Error en metodo createHistorialpenal:");
			e.printStackTrace();
		} finally {
			em.close();
		}

	}

	public static void updateHistorialpenal(Historialpenal historialPenal) {
		try {
			em = jpaUtils.getEntityManager();
			em.getTransaction().begin();
			em.merge(historialPenal);
			em.getTransaction().commit();

		} catch (Exception e) {
			System.out.println("Error en metodo updateHistorialpenal:");
			e.printStackTrace();
		} finally {
			em.close();
		}
	}
	public static void deleteHistorialPenal(int idHistorialPenal) {
		try {
			em = jpaUtils.getEntityManager();
			Historialpenal h = em.find(Historialpenal.class, idHistorialPenal);
			em.getTransaction().begin();
			em.remove(h);
			em.getTransaction().commit();

		} catch (Exception e) {
			System.out.println("Error en metodo deleteHistorialPenal:");
			e.printStackTrace();
		} finally {
			em.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<Historialpenal> findHistorialesByExpediente(
			int idExpediente) {
		List<Historialpenal> historiales = new ArrayList<Historialpenal>();
		try {
			em = jpaUtils.getEntityManager();
			Query q = em
					.createQuery(
							"SELECT OBJECT(Historialpenal) FROM Historialpenal historialpenal WHERE historialpenal.expedienteBean.idExpediente= :valor")
					.setParameter("valor", idExpediente);
			historiales = q.getResultList();
		}catch (NoResultException e) {
			System.out.println("No hay historiales penales.");
		} 
		catch (Exception e) {
			System.out.println("Error en metodo findHistorialesByExpediente");
			e.printStackTrace();
		} finally {
			em.close();
		}
		return historiales;
	}

}
